package cn.lixin.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component // 交给容器管理！！！！
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token"); // token保存在请求头
        if (!StringUtils.isEmpty(token)){ // token 有值
            Object logininfo = redisTemplate.opsForValue().get(token); // 根据token获取登录信息
            if (logininfo != null) { // 如果登录信息不为空 还存在（没有过期）
                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES); // 重新保存30分钟信息
                return true; // 放行
            }

        }
        // 没有登录 token == null 或者过期 logininfo== null 需要拦截
        response.setContentType("application/json;charset=UTF-8");  // 编码集
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();// 获取输出流 {“success”:false,"massege":"没有登录哦"}
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();
        return false;
    }
}
